# -*- coding:utf-8 -*-
import math
import sys

from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from PyQt5.QtCore import Qt, QMargins, QRect
from PyQt5.QtGui import QPainter, QColor, QBrush, QFont
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy, QApplication


class PieCenterLabel(QWidget):
    __labelTop = None
    __labelBottom = None

    def __init__(self, parent=None):
        super(PieCenterLabel, self).__init__(parent)
        layout = QVBoxLayout()
        self.__labelTop = QLabel(self)
        self.__labelBottom = QLabel(self)
        self.__labelTop.setAlignment(Qt.AlignCenter)
        self.__labelBottom.setAlignment(Qt.AlignCenter)
        self.__labelTop.setContentsMargins(0, 8, 0, 0)
        self.__labelBottom.setContentsMargins(0, 0, 0, 0)
        self.__labelTop.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.__labelBottom.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addWidget(self.__labelTop)
        layout.addWidget(self.__labelBottom)
        self.setStyleSheet("background: transparent")
        self.__labelTop.setStyleSheet("background: transparent; color:white;")
        self.__labelBottom.setStyleSheet("background: transparent; color:rgb(0,254,102);")
        #self.setStyleSheet("background-color: blue;")
        #self.__labelTop.setStyleSheet('background-color: yellow;')
        #self.__labelBottom.setStyleSheet('background-color: gray;')
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

    def setText(self, valueTop, valueBottom):
        bNeedCallResize = False
        if len(self.__labelTop.text()) == 0 and len(self.__labelBottom.text()) == 0:
            bNeedCallResize = True
        self.__labelTop.setText(valueTop)
        self.__labelBottom.setText(valueBottom)
        if bNeedCallResize:
            self.__resizeFont()

    def clear(self):
        self.__labelTop.setText('')
        self.__labelBottom.setText('')

    def __resizeFont(self):
        width = self.width()
        height = self.height() // 2
        count = max(len(self.__labelTop.text()), len(self.__labelBottom.text()))
        if count > 0:
            new_font_size = width // count
            if new_font_size > height:
                new_font_size = height
            new_font_size += 6
            # print(f'w:{width}, h:{height}, new_font_size:{new_font_size}, char count:{count}')
            # self.font().setPixelSize(new_font_size)
            newFont = QFont('微软雅黑')
            newFont.setPixelSize(new_font_size)
            self.__labelTop.setFont(newFont)
            new_font_size += 6
            newFont.setBold(True)
            newFont.setPixelSize(new_font_size)
            self.__labelBottom.setFont(newFont)

    def resizeEvent(self, event):
        self.__resizeFont()
        return super().resizeEvent(event)


class PieChart(QWidget):
    __centerWidget = None
    __series = None
    __pieSliceList = []
    __chart = None
    __chartView = None

    __minFixedGap = 0  # 固定边距
    __holeRate = 0.7

    def __init__(self, parent=None):
        super(PieChart, self).__init__(parent)
        self.setGeometry(QRect(0, 0, 120, 120))
        layout = QVBoxLayout(self)
        self.__centerWidget = PieCenterLabel()
        self.__series = QPieSeries()
        self.__series.setHoleSize(self.__holeRate)
        self.__series.setPieSize(1)
        self.__series.setPieStartAngle(90)
        self.__series.setPieEndAngle(-270)

        # 创建图表
        self.__chart = chart = QChart()
        chart.setContentsMargins(0, 0, 0, 0)
        chart.setMargins(QMargins(self.__minFixedGap, self.__minFixedGap, self.__minFixedGap, self.__minFixedGap))
        chart.addSeries(self.__series)
        chart.legend().hide()
        chart.setBackgroundBrush(QColor(30, 30, 30))
        #chart.setStyleSheet("background-color: pink;")

        # 图表视图
        self.__chartView = chartView = QChartView(chart)
        chartView.setContentsMargins(0, 0, 0, 0)
        chartView.setRenderHint(QPainter.Antialiasing)
        chartView.setStyleSheet("background: transparent;")
        self.__resizeCenterWidget()
        chartView.scene().addWidget(self.__centerWidget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(chartView)
        self.setLayout(layout)

    def __resizeCenterWidget(self):
        rect = self.__chartView.geometry()
        pnt = rect.center()
        minLen = min(rect.width(), rect.height())
        pieRctEdgeLen = minLen - self.__minFixedGap
        holeRadius = math.floor(pieRctEdgeLen*self.__holeRate/2)
        maxCenterRctEdgeLen = math.floor(math.sqrt(holeRadius*holeRadius/2))
        maxCenterRctEdgeLen -= 2
        rect = QRect(pnt.x() - maxCenterRctEdgeLen, pnt.y() - maxCenterRctEdgeLen, maxCenterRctEdgeLen*2, maxCenterRctEdgeLen*2)
        self.__centerWidget.setGeometry(rect)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.__resizeCenterWidget()

    # 设置OK的比例（浮点数）, 100表示100%
    def setValue(self, valueOk):
        if len(self.__pieSliceList) == 2:
            self.__pieSliceList[0].setValue(valueOk)
            self.__pieSliceList[1].setValue(100-valueOk)
        else:
            self.__pieSliceList = [QPieSlice('OK', valueOk), QPieSlice('NG', 100-valueOk)]
            self.__series.append(self.__pieSliceList)
            self.__pieSliceList[0].setBrush(QColor(0, 134, 255))
            self.__pieSliceList[1].setBrush(QColor(114, 114, 114))
            self.__pieSliceList[0].setBorderColor(QColor(0, 134, 255))
            self.__pieSliceList[1].setBorderColor(QColor(114, 114, 114))
            self.__pieSliceList[0].setBorderWidth(0)
            self.__pieSliceList[1].setBorderWidth(0)

        self.__centerWidget.setText(f'{valueOk:.1f}%', 'OK')

    # 清除饼图（饼图不再显示）
    def clear(self):
        self.__series.clear()
        self.__pieSliceList = []
        self.__centerWidget.clear()




if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = PieChart()
    w.setValue(0.5)
    w.setValue(98.5643)
    w.clear()
    w.setValue(8.5643)
    # w.resize(200, 300)
    # w.resize(150, 150)
    w.show()
    sys.exit(app.exec_())

